<template>
  <div id="store-list" v-if="showPage">
    <el-card class="mg-b-10">
      <el-row>
        <el-col :span="5" class="setDate">
          <el-radio-group
            v-model="checkedDates"
            fill="#e2211c"
            size="mini"
            text-color="#fff"
            @change="selectDate"
          >
            <el-radio-button v-for="(date ,index) in dates" :label="date" :key="index">{{date}}</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="5">
          <el-select
            class="select-prefix"
            size="mini"
            v-model="storeNo"
            placeholder="请选择门店"
            clearable
            filterable
            style="margin-right: 30px"
          >
            <template slot="prefix">
              <span class="prefixSlot">选择门店</span>
            </template>
            <el-option-group v-for="group in storeList" :key="group.cityId" :label="group.city">
              <el-option
                v-for="item in group.list"
                :key="item.storeNo"
                :label="item.storeName"
                :value="item.storeNo"
              ></el-option>
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="12">
          <span class="storeInfo">拓展负责人：优爆爆</span>
          <span class="storeInfo">运营负责人：优爆爆</span>
          <span class="storeInfo">区域：河北省/石家庄市/石家庄县</span>
        </el-col>
        <el-col :span="2" class="col_float_right">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="handleChangeSearch"
          >查 询</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-row class="saleState mg-b-10">
      <el-col :span="showSalesTable == '表格' ? 18 : 24 " class="left">
        <el-card>
          <div class="card-header">
            <h2>销售情况-图表</h2>
            <div>
              <el-radio-group
                v-model="showSalesTable"
                @change="isHideSalesTable"
                size="mini"
                fill="#e2211c"
                :border="true"
                text-color="#fff"
              >
                <el-radio-button label="图表"></el-radio-button>
                <el-radio-button label="表格"></el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <echartsTpl
            :id="'container'"
            ref="saleEcharts"
            :height="'260px'"
            :width="saleStateWidth"
            :options="options"
          ></echartsTpl>
        </el-card>
      </el-col>
      <el-col :span=" showSalesTable == '表格' ? 6 : 0" class="right">
        <el-card>
          <div class="card-header">
            <h2>销售情况-表格</h2>
            <el-button
              size="mini"
              type="primary"
              icon="iconfont excel"
              @click="downLoadDailysales"
            >导出</el-button>
          </div>
          <el-table stripe :data="salesData" border height="250">
            <el-table-column label="日期" prop="dateName" :width="90"></el-table-column>
            <el-table-column label="销售额" prop="totalSaleAmount"></el-table-column>
            <el-table-column label="销量" prop="totalSaleQuantity"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="mg-b-10">
      <div class="card-header">
        <h2>商品销存</h2>
        <el-button size="mini" type="primary" icon="iconfont excel" @click="downLoadStorekeys">导出</el-button>
      </div>
      <el-table stripe :data="removeStock.list" border height="340">
        <el-table-column label="品牌名称" prop="brandName" width="90"></el-table-column>
        <el-table-column label="商品名称" prop="goodsName" show-overflow-tooltip width="200"></el-table-column>
        <el-table-column label="品类" prop="categoryName" show-overflow-tooltip width="200"></el-table-column>
        <el-table-column label="款号" prop="goodsCode"></el-table-column>
        <el-table-column label="销量" prop="totalSaleQuantity" width="50"></el-table-column>
        <el-table-column label="销售额" prop="totalSaleAmount"></el-table-column>
        <!-- <el-table-column label="日均销售额" prop="avgSaleAmount"></el-table-column> -->
        <el-table-column label="期初库存" prop="beginStockQuantity" width="100"></el-table-column>
        <el-table-column label="期末库存" prop="finalStockQuantity" width="100"></el-table-column>
        <el-table-column label="周转天数" prop="trunoverDay" width="70"></el-table-column>
        <el-table-column label="在店天数" prop="stayatDay" width="70">
           <template slot-scope="scope">
            <span>{{ scope.row.stayatDay == -1 ? '-':  scope.row.stayatDay}}</span>
          </template>
        </el-table-column>
      </el-table>
      <page
        v-if="removeStock.total"
        :total="removeStock.total"
        :page="removeStock.page"
        :size="removeStock.size"
        @handlepagechange="handlePageChange"
        @handleSizeChange="handleSizeChange"
      ></page>
    </el-card>
  </div>
</template>
<script>
// import echarts from "echarts"
import echartsTpl from "../../commonComponents/echarts"
import { getDay } from "../../../api/commonJs/getDays"
import page from '../../commonComponents/page'

const dateOptions = ['近7天', '近15天', '近30天'];
export default {
  components: { echartsTpl, page },
  data() {
    return {
      showPage: false, //页面显示
      checkedDates: dateOptions[0],
      dateScope: "",//选择日期范围
      storeNo: "",//选择门店
      dates: dateOptions,
      storeList: [],
      saleStateWidth: '100%', //echarts宽度
      showSalesTable: "图表", //显示销售状况表格
      options: {
        color: ['#e60012', '#22ce00'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          show: true,
          left: 60,
          data: ["销售额","销量"]
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '20px',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: [],
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
           {
              type: 'value',
              scale: true,
              name: '销售额',
          },
          {
              type: 'value',
              scale: true,
              name: '销量',
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'bar',
            barWidth: '60%',
            label: {
              normal: {
                show: true,
              }
            },
            data: []
          },
          {
            name: '销量',
            type: 'line',
            yAxisIndex: 1,
            label: {
              normal: {
                show: true,
              }
            },
            data: []
          }
        ]
      },
      salesData: [],
      removeStock: {
        list: [],
        page: 1,
        size: 10,
        total: 0
      },
      downUrl: process.env.BASE_API + '/youbao/report/api/download/storeview'
    };
  },
  mounted() {
    this.getStoreListByGroup()
    this.initData()
  },
  methods: {
    /**页面初始化*/
    initData() {
      let checkedDates = this.checkedDates;
      this.handleSelectDays(checkedDates);
      this.handlePageData(() => {
        this.showPage = true
      });
    },
     /**获取参数*/
    getParams() {
      let { dateScope, storeNo } = this,
        dateFrom = this.formate(dateScope[0].getTime(), "yyyyMMdd"),
        dateTo = this.formate(dateScope[1].getTime(), "yyyyMMdd");
      let params = {
        dateFrom: Number(dateFrom), //开始时间
        dateTo: Number(dateTo),//结束时间
        storeNo: storeNo + "", //门店编码
        storeType: -1
      }
      return params;
    },
    /**页面数据渲染*/
    handlePageData(cb, loadStockData) {
      let params = this.getParams();
      if (loadStockData && loadStockData != '') {
        this.getSalenstockList(params).then(res => {
          cb && cb()
        }).catch(err => {
          cb && cb()
        })
      } else {
        Promise.all([this.getDailysales(params), this.getSalenstockList(params)]).then(res => {
          cb && cb()
        }).catch(err => {
          cb && cb()
        })
      }
    },
    /**获取店铺数据*/
    getStoreListByGroup() {
      this.$server.salesExhibitionApi.getStore().then(res => {
        this.storeList = res.data
      })
    },
    /**获取销售状况*/
    getDailysales(params) {
      let { options } = this, xAxis = options["xAxis"];
      return new Promise((reslove, reject) => {
        this.$server.salesExhibitionApi.getDailysale(params).then(res => {
          let series = options.series, data = res.data, salesData = [];

          series[0]["data"] = data.totalSaleAmountList;
          series[1]["data"] = data.totalSaleQuantityList;
          this.$set(this.options, 'series', series);

          this.saleStateWidth = data.dateList.length > 15 ? data.dateList.length * 60 + 'px' : '100%';

          xAxis[0]["data"] = data.dateList.map(item => {
            item = item + "";
            return item.substr(4, 2) + "." + item.substr(6, 2)
          });
          

          this.$set(this.options, 'xAxis', xAxis);
          data.dateList.forEach((item, index) => {
            item = item + "";
            item = item.substr(0, 4) + "-" + item.substr(4, 2) + "-" + item.substr(6, 2);

            salesData[index] = {
              "dateName": item,
              "totalSaleAmount": data.totalSaleAmountList[index],
              "totalSaleQuantity": data.totalSaleQuantityList[index]
            }
          })
          this.salesData = salesData;
          reslove(data)
        })
      })
    },
    /**获取商品销存列表*/
    getSalenstockList(params) {
      let { removeStock } = this;
      return new Promise((reslove, reject) => {
        let pageInfo = {
          page: removeStock.page,
          size: removeStock.size
        }
        this.$server.salesExhibitionApi.getSalenstock(pageInfo, params).then(res => {
          let data = res.data;
          this.$set(this.removeStock, "list", data);
          this.$set(this.removeStock, "total", res.total);

          reslove(res.data)
        })
      })
    },
    /**商品销存导出*/
    downLoadStorekeys() {
      let params = this.getParams();
      try {
        let obj = {
          url: this.downUrl + '/salenstock/excel',
          name: '商品销存' + params.dateFrom + '-' + params.dateTo,
          params: params
        }
        this.$server.excelApi.downLoadExcelPost(obj)
      } catch (err) { this.$paramsError(err) }
    },
     /**销售情况导出*/
    downLoadDailysales() {
      let params = this.getParams();
      try {
        let obj = {
          url: this.downUrl + '/dailysale/excel',
          name: '销售情况' + params.dateFrom + '-' + params.dateTo,
          params: params
        }
        this.$server.excelApi.downLoadExcelPost(obj)
      } catch (err) { this.$paramsError(err) }
    },
    /**日期范围处理*/
    handleSelectDays(val) {
      switch (val) {
        case dateOptions[0]:
          this.dateScope = [new Date(getDay(-7)), new Date(getDay(-1))];
          break;
        case dateOptions[1]:
          this.dateScope = [new Date(getDay(-15)), new Date(getDay(-1))];
          break;
        case dateOptions[2]:
          this.dateScope = [new Date(getDay(-30)), new Date(getDay(-1))];
          break;
      }
    },
    /** 销售情况图标x轴数据*/
    doDaySalesData() {
      let { dateScope } = this;
      let dayLen = parseInt((dateScope[1].getTime() - dateScope[0].getTime()) / 1000 / 60 / 60 / 24),
        curDate = new Date(this.formate(dateScope[1].getTime(), "yyyy/MM/dd")),
        days = [];
      for (let i = dayLen - 1; i >= 0; i--) {
        curDate.setDate(curDate.getDate() - 1);
        days.unshift(this.formate(curDate, 'MM.dd'));
      }
      return days;
    },
    /**查询*/
    handleChangeSearch() {
      this.handlePageData(() => {
        this.$refs.saleEcharts.uploadData();
      });
    },
    /**分页*/
    handlePageChange(page) {
      this.$set(this.removeStock, "page", page)
      this.handlePageData(() => { }, true);
    },
    /**切换size*/
    handleSizeChange(size) {
      this.$set(this.removeStock, "size", size)
      this.handlePageData(() => { }, true);
    },
    /**隐藏或展示销售状况表格*/
    isHideSalesTable(e) {
      let oldShowTab = this.showSalesTable, that = this;
      this.showSalesTable = e;
      setTimeout(() => {
        that.$refs.saleEcharts.uploadData();
      }, 200)
    },
    /**选中日期*/
    selectDate(e) {
      let that = this
      this.handleSelectDays(e);
      this.handlePageData(() => {
        that.showPage = true
        that.$refs.saleEcharts.uploadData();
      })
    },
  }
};
</script>
<style lang="less" scoped>
.storeInfo,
.dateTitle {
  font-size: 12px;
  color: #666666;
}
.storeInfo:not(:first-child) {
  margin-left: 10px;
}
.setDate {
  display: flex;
  align-items: center;
}
.dateTitle {
  margin-right: 20px;
}
.saleState {
  .left {
    padding-right: 5px;
    transition: all 0.2s;
  }
  .right {
    padding-left: 5px;
    height: 342px;
    transition: all 0.2s;
    .el-card,
    .el-card__body {
      height: 100%;
    }
  }
}
.card-header {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  h2 {
    font-size: 14px;
    color: #666;
    font-weight: normal;
  }
  .showSalesTable {
    font-size: 24px;
    cursor: pointer;
    transition: all 0.2s;
    // transform: rotate(45deg);
  }
  .el-radio-button--mini.commonShow .el-radio-button__inner {
    padding: 0 !important;
    i {
      font-size: 14px;
    }
  }
}
</style>